package a66weding.com.jiehuntong.fragment;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;

import java.io.File;
import java.lang.ref.SoftReference;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.ToolsWedRegisterActivity;
import a66weding.com.jiehuntong.beans.WedRegistryMapBean;
import a66weding.com.jiehuntong.common.CommonAdapter;
import a66weding.com.jiehuntong.common.MyViewHolder;
import a66weding.com.jiehuntong.common.utils.CUtils;

/**
 * @version :
 * @creator : AxDu
 * @create-time : 2016/6/7
 * @description :
 */
public class Tools_WedRegMainFragment extends BaseToolsDayPlanFragment implements View.OnClickListener {
    private ToolsWedRegisterActivity mRegistryActivity;
    private MapView mMapview;
    private ListView mplaceLv;
    private PoiCitySearchOption poiCitySearchOption;
    private PoiSearch poiSearch;

    private TextView mText;
    private TextView mTextCount;
    private TextView mCityNameTv;
    private LinearLayout mBackView;
    private TextView mToGohereTv;
    private ImageView mLocationIv;
    private TextView mToCallIv;
    private LinearLayout mPlaceLay;
    private TextView mFirstNumTv;
    private TextView mCancelTv;

    private Fragment mFragment;

    private WedRegistryMapBean mCurrentMapBean;


    private int index;
    private List<WedRegistryMapBean> addressList;
    private String mCurrentPhoneNum;


    private View mContentView;
    private PopupWindow mTelphonePopWindow;

    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mRegistryActivity = (ToolsWedRegisterActivity) getActivity();
    }


    @Override
    public View initView() {
        mContentView = View.inflate(mRegistryActivity, R.layout.pager_tools_wedregister, null);

        mMapview = (MapView) mContentView.findViewById(R.id.bmapview);
        mRegistryActivity.setmMapView(mMapview);
        mBackView = (LinearLayout) mContentView.findViewById(R.id.llay_tools_wedregister_back);
        mplaceLv = (ListView) mContentView.findViewById(R.id.lview_tools_wedregister_content);
        mTextCount = (TextView) mContentView.findViewById(R.id.tv_tools_dayplan_title);
        mCityNameTv = (TextView) mContentView.findViewById(R.id.tv_tools_wedregistry_place);
        mPlaceLay = (LinearLayout) mContentView.findViewById(R.id.lay_tools_wedregister_place);
        mTextCount.setOnClickListener(this);
        mBackView.setOnClickListener(this);
        mPlaceLay.setOnClickListener(this);
        mTextCount.setOnClickListener(this);
        return mContentView;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void initData() {

        String cityName = mRegistryActivity.getCityName();
        mCityNameTv.setText(cityName);
        //初始化百度地图
        poiSearch = PoiSearch.newInstance();
        poiCitySearchOption = new PoiCitySearchOption().city(mCityNameTv.getText().toString().trim())
                .keyword("婚姻登记处");
        poiCitySearchOption.pageCapacity(20);// 默认每页20条
        poiCitySearchOption.pageNum(0);// 分页编号
        poiSearch.setOnGetPoiSearchResultListener(onGetPoiSearchResultListener);

        poiSearch.searchInCity(poiCitySearchOption);

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.llay_tools_wedregister_back:
                mMapview.onPause();
                mMapview.onDestroy();
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.remove(this);
                mRegistryActivity.finish();
                break;
            case R.id.tv_tools_wedregistry_gohere:
                int tag = (int) view.getTag();
                WedRegistryMapBean mapBean = addressList.get(tag);
                startBaiduMap(mapBean);
                break;
            case R.id.iv_tools_wedregister_location://定位

                mCurrentMapBean = (WedRegistryMapBean) view.getTag();
                mRegistryActivity.setmCurrentMapBean(mCurrentMapBean);

                mRegistryActivity.setFragment("选择地点");

                break;
            case R.id.lay_tools_wedregister_place://选择城市

                mRegistryActivity.setFragment("城市选择");

                break;
            case R.id.tv_tools_wedreg_telephone://打电话
                mCurrentMapBean = (WedRegistryMapBean) view.getTag();
                mCurrentPhoneNum = mCurrentMapBean.getPhoneNum();
                //判断权限
                int checkCallPhonePermission = ContextCompat.checkSelfPermission(getActivity(),Manifest.permission.CALL_PHONE);
                if (checkCallPhonePermission!= PackageManager.PERMISSION_GRANTED){
                    ActivityCompat.requestPermissions(getActivity(),new String[]{Manifest.permission.CALL_PHONE},REQUEST_CODE_ASK_CALL_PHONE);
                    return;
                }else{
                    showPopupWindow(view);
                }

                break;
            case R.id.tv_telephone_cancel://pop取消
                if (mTelphonePopWindow != null) {
                    mTelphonePopWindow.dismiss();
                }

                break;
            case R.id.tv_firstnum://拨打电话
                if(!TextUtils.isEmpty(mCurrentPhoneNum)) {
                    if(mTelphonePopWindow!=null) {
                        mTelphonePopWindow.dismiss();
                    }
                    toCallPhone(mCurrentPhoneNum);
                }else {
                    CUtils.showToast("电话号码异常");
                }
                break;
            case R.id.tv_tools_dayplan_title://测试


                break;

        }
    }


    OnGetPoiSearchResultListener onGetPoiSearchResultListener = new OnGetPoiSearchResultListener() {

        @Override
        public void onGetPoiResult(PoiResult poiResult) {

            try {
                int totalPoiNum = poiResult.getTotalPoiNum();

                List<PoiInfo> allPoi = poiResult.getAllPoi();
                addressList = new ArrayList<WedRegistryMapBean>();
                WedRegistryMapBean addressBean = null;
                for (PoiInfo poiInfo : allPoi) {
                    String name = poiInfo.name;
                    String address = poiInfo.address;
                    String phoneNum = poiInfo.phoneNum;

                    String postCode = poiInfo.postCode;
                    boolean isPano = poiInfo.isPano;
                    String uid = poiInfo.uid;

                    LatLng location = poiInfo.location;


                    PoiDetailSearchOption poiDetailSearchOption = new PoiDetailSearchOption();
                    poiDetailSearchOption.poiUid(uid);

                    String shopTime = "周一至周五 (法定节假日除外) 8:30-11:30 14:00-16:30";

                    addressBean = new WedRegistryMapBean(name, address, shopTime, phoneNum, location);
                    addressBean.setUid(uid);
                    addressList.add(addressBean);

                    poiSearch.searchPoiDetail(poiDetailSearchOption);

                }

                if (addressList.size() > 0) {
                    mplaceLv.setAdapter(new CommonAdapter<WedRegistryMapBean>(mRegistryActivity, addressList, R.layout.item_tools_wedregister_placeitem) {
                        @Override
                        public void convert(MyViewHolder holder, int position) {
                            WedRegistryMapBean wedRegistryMapBean = addressList.get(position);

                            holder.setText(R.id.label_name, wedRegistryMapBean.getTitle());
                            holder.setText(R.id.label_address, wedRegistryMapBean.getAddress());
                            holder.setText(R.id.label_time, wedRegistryMapBean.getShopTime());

                            mToGohereTv = (TextView) holder.getView(R.id.tv_tools_wedregistry_gohere);
                            mLocationIv = (ImageView) holder.getView(R.id.iv_tools_wedregister_location);
                            mToCallIv = (TextView) holder.getView(R.id.tv_tools_wedreg_telephone);

                            mLocationIv.setTag(wedRegistryMapBean);
                            mLocationIv.setOnClickListener(Tools_WedRegMainFragment.this);

                            mToGohereTv.setTag(position);
                            mToGohereTv.setOnClickListener(Tools_WedRegMainFragment.this);

                            mToCallIv.setTag(wedRegistryMapBean);
                            mToCallIv.setOnClickListener(Tools_WedRegMainFragment.this);

                        }
                    });

                } else {
                    //没有找到结果

                }


                BitmapFactory bitmapFactory = new BitmapFactory();

                Bitmap bitmap = bitmapFactory.decodeResource(getResources(), R.mipmap.icon_map_mark2);

                SoftReference<Bitmap> bitmapcache = new SoftReference<Bitmap>(bitmap);

                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);

                // 构建MarkerOption，用于在地图上添加Marker
                OverlayOptions option = new MarkerOptions().position(addressList.get(0).getLocation()).icon(bitmapDescriptor);
                double latitude = addressList.get(0).getLocation().latitude;
                double longitude = addressList.get(0).getLocation().longitude;
                LatLng center = new LatLng(latitude,longitude);
                MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLngZoom(center, 18);
                mMapview.getMap().setMapStatus(mapStatus);
                mMapview.getMap().addOverlay(option);


                String poiname = poiResult.getAllPoi().get(0).name;
                String poiadd = poiResult.getAllPoi().get(0).address;
                String idString = poiResult.getAllPoi().get(0).uid;

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailInfo) {


            String address = poiDetailInfo.getAddress();
            String shopHours = poiDetailInfo.getShopHours();
            String telephone = poiDetailInfo.getTelephone();
            int grouponNum = poiDetailInfo.getGrouponNum();
            int checkinNum = poiDetailInfo.getCheckinNum();


        }
    };


    public void startBaiduMap(WedRegistryMapBean mapBean) {

        if(isInstallByread("com.baidu.BaiduMap")){

        }else{
            CUtils.showToast("调用百度地图失败！请确认您的手机上是否安装了百度地图");
            return;
        }

        String uid = mapBean.getUid();

        Intent intent = null;
        try {
            intent = Intent.parseUri("intent://map/place/detail?uid=" + uid + "&src=66结婚网#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end", 0);
            startActivity(intent); //启动调用

        } catch (URISyntaxException e) {
            e.printStackTrace();
            CUtils.showToast("调用百度地图失败！");


        }



    }

    /**
     * 判断是否安装目标应用
     * @param packageName 目标应用安装后的包名
     * @return 是否已安装目标应用
     */
    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }


    public MapView getMapview() {

        return mMapview;
    }


    private void showPopupWindow(View view) {

        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(mActivity).inflate(
                R.layout.pop_tools_wedreg_phone, null);
        mFirstNumTv = (TextView) contentView.findViewById(R.id.tv_firstnum);
//        mSecondNumTv = (TextView) contentView.findViewById(R.id.tv_secondnum);
        mCancelTv = (TextView) contentView.findViewById(R.id.tv_telephone_cancel);
        if (!TextUtils.isEmpty(mCurrentPhoneNum)) {
            mFirstNumTv.setText(mCurrentPhoneNum);
            mFirstNumTv.setOnClickListener(Tools_WedRegMainFragment.this);
        } else {
            mFirstNumTv.setText("抱歉，未查询到电话信息");
            mFirstNumTv.setCompoundDrawables(null, null, null, null);
            mFirstNumTv.setEnabled(false);
        }

        mCancelTv.setOnClickListener(Tools_WedRegMainFragment.this);
        mFirstNumTv.setOnClickListener(Tools_WedRegMainFragment.this);



        mTelphonePopWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);



        //点击空白处时，隐藏掉pop窗口
        mTelphonePopWindow.setTouchable(true);
        mTelphonePopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        mTelphonePopWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return true;
            }
        });

        //设置位置
        mTelphonePopWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);


    }

    public void toCallPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNum));


        if (ActivityCompat.checkSelfPermission(mRegistryActivity, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mRegistryActivity.startActivity(intent);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case REQUEST_CODE_ASK_CALL_PHONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showPopupWindow(mToCallIv);
                } else {
                    Toast.makeText(getActivity(), "请设置电话权限", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
